import { reactive, ref, computed } from 'vue';
import { ElMessage } from 'element-plus'

// useStorage 让本地存储变成响应式 不需要去操作本地存储
import {StorageSerializers, useStorage} from '@vueuse/core';

// 需要一个变量记录登录的user，初始的状态是空的
// 放到最外层，避免被回收掉
// const user = ref()

// useStorage(键明, 初始值, 范围, 系列化：转换为JSON字符串)
const user = useStorage('user', null, sessionStorage, {
  serializer: StorageSerializers.object
})


export function useUser() {
  const loginForm = reactive({
  username: '',
  password: ''
  })
  
  // 请求接口
  const loginFn = () => {
    user.value = {
      id: 1,
      username: loginForm.username
    }
    ElMessage.success('登录成功')
  }

  const logoutFn = () => {
    loginForm.username = null
    loginForm.password = null
    user.value = null
    ElMessage.success('退出登录')
  }

  const status = computed(() => user.value?.id)

  return {
    loginForm,
    user,
    loginFn,
    logoutFn,
    status
  }
}
